import {
  getCourseDetailById,
  getAllVideoByCourseId,
  getCourseCommentList,
  addCourseComment
} from "@/api/course/index";
import {
  getUserVideoRecord,
  addUserVideoRecord,
  updateStudyDuration
} from "@/api/video/index";
import { useRoute } from "vue-router";
import { onMounted, reactive, ref, onBeforeUnmount, computed } from "vue";
import { useUserStoreHook } from "@/store/modules/user";
import { ElMessage } from "element-plus";
import Dplayer from "dplayer";
import { VIDEOURL, BASEURL } from "@/config/urlConfig";

export function useVideoHooks() {
  const route = useRoute();

  const userStore = useUserStoreHook();

  const userInfo = computed(() => userStore.userInfo);
  const token = computed(() => userStore.token);

  const couresId = route.query.courseId;
  const videoIndex = route.query.index || 0;
  // const videoId = route.query.videoId;

  let courseData = reactive<any>({});
  const videoList = ref<any>([]);
  const videoRef = ref();

  async function getCourseDetail() {
    const res = await getCourseDetailById({ id: couresId });

    courseData = Object.assign(courseData, res.data);
  }

  async function getVideoByCourseIdFun() {
    const res = await getAllVideoByCourseId({ id: couresId });

    videoList.value = res.data;
    currentVideoUrl.value = videoList.value[Number(videoIndex)].videoUrl;
    currentVideoId.value = videoList.value[Number(videoIndex)].id;

    getUserVideoRecordFun();
    // videoRef.value.
    initDplayer();
    dPlayer.value.danmaku.show();
    // dPlayer.value.seek(videoRecord.studyDuration);
  }

  // ------------------------视频---------------
  const currentVideo = ref(0);
  const currentVideoUrl = ref("");
  const currentVideoId = ref("");
  let videoRecord = reactive<any>({});

  const dPlayer = ref<any>();

  currentVideo.value = Number(videoIndex);

  async function getUserVideoRecordFun() {
    const res = await getUserVideoRecord({
      userId: userInfo.value.userId,
      videoId: currentVideoId.value
    });

    videoRecord = Object.assign(videoRecord, res.data);

    if (res.code == 201) {
      await addUserVideoRecord({
        userId: userInfo.value.userId,
        videoId: currentVideoId.value,
        courseId: couresId,
        studyDuration: 0
      });
    }
  }

  async function updateStudyDurationFun() {
    const time = dPlayer.value.video?.currentTime;
    await updateStudyDuration({
      userId: userInfo.value.userId,
      videoId: currentVideoId.value,
      couresId: couresId,
      studyDuration: time
    });
  }

  async function videoClick(item: any, index: number) {
    await updateStudyDurationFun();
    currentVideoUrl.value = item.videoUrl;
    currentVideoId.value = item.id;
    currentVideo.value = index;

    await getUserVideoRecordFun();

    dPlayer.value.switchVideo(
      {
        url: VIDEOURL + item.videoUrl,
        type: "auto"
      },
      {
        id: item.id,
        api: BASEURL + "/danmaku/videoDanmaku",
        token: token.value,
        user: userInfo.value.userId,
        bottom: "15%"
      }
    );

    // dPlayer.value.seek(videoRecord.studyDuration);
  }

  function initDplayer() {
    dPlayer.value = new Dplayer({
      //初始化视频对象
      container: videoRef.value, //指定视频容器节点
      autoplay: true,
      theme: "#FADFA3",
      loop: false,
      lang: "zh-cn",
      screenshot: true,
      // hotkey: true,
      // preload: "auto",
      volume: 0.7,
      mutex: true,
      video: {
        url: VIDEOURL + currentVideoUrl.value,
        // pic: "dplayer.png",
        // thumbnails: "thumbnails.jpg",
        type: "auto"
      },
      danmaku: {
        id: currentVideoId.value,
        api: BASEURL + "/danmaku/videoDanmaku",
        token: token.value,
        // maximum: 1000,
        // addition: [
        //   "https://dplayer.alone88.cn/v3/bilibili?aid=BV19w411T7pk&cid=313938332"
        // ]
        user: userInfo.value.userId,
        bottom: "15%"
        // unlimited: true,
        // speedRate: 0.5
      }
      // contextmenu: [
      //   {
      //     text: "custom1",
      //     link: "https://github.com/DIYgod/DPlayer"
      //   },
      //   {
      //     text: "custom2",
      //     click: (player: any) => {
      //       console.log(player);
      //     }
      //   }
      // ],
      // highlight: [
      //   {
      //     time: 20,
      //     text: "这是第 20 秒"
      //   },
      //   {
      //     time: 120,
      //     text: "这是 2 分钟"
      //   }
      // ]
    });
  }

  // ------------------- 评论 ---------------------------
  const commentList = ref<any>([]);
  async function getCourseCommentListFun() {
    const res = await getCourseCommentList({ id: couresId });

    commentList.value = res.data;
  }

  async function sendBtn(val: string, data: any) {
    console.log(val, data);
    // if (data) {
    // } else {

    // }
    const rootCmId = data?.rootCommentId ? data.rootCommentId : data?.id;
    const res = await addCourseComment({
      content: val,
      courseId: couresId,
      rootCommentId: rootCmId,
      toUserId: data ? data.userId : null,
      userId: userStore.getUserInfo?.userId
    });

    console.log(res);
    if (res.code === 200) {
      getCourseCommentListFun();
      ElMessage.success("发表成功！");
    }
  }

  onMounted(() => {
    getCourseDetail();
    getCourseCommentListFun();
    getVideoByCourseIdFun();
  });

  onBeforeUnmount(async () => {
    updateStudyDurationFun();
    dPlayer.value.destroy();
  });

  return {
    videoRef,
    courseData,
    videoList,
    currentVideo,
    currentVideoUrl,
    commentList,
    videoClick,
    sendBtn
  };
}
